<!--
 * @LastEditors: Yang.Zzz
 * @LastEditTime: 2024-05-17 15:42:33
-->
<script setup>
import TaskList from './taskList.vue'
import { onMounted, reactive, ref ,computed , watch  } from "vue";
import { useStore } from 'vuex'
import { useRoute, useRouter } from "vue-router";
import instance  from '../utils/api'
import { user_mock}   from '../utils/mock'
import { ElMessage } from 'element-plus'
 
const form = reactive({
                    countryNum: undefined,
                    phoneNumber: '',
                    verificationCode: '',
                    email: '',
                    password: '',
                    confirmPassword: '',
                })

                const emailForm = reactive({
                    email: '',
                    verificationCode: '',
                    password: '',
                    confirmPassword: '',
                })

                const isCheckProtocol = ref(false) // 是否勾选协议

                const handleSureNumberInputValue = (key,val) => {
                    let _form;
                    _form = tabSelectItem.value === 'phone' ? form : emailForm 
                    _form[key] = val.replace(/[^\d]/g, ''); 
                }

                watch(  
                    () => form.phoneNumber, // 依赖项  
                    (newVal) => { // 回调函数  
                        handleSureNumberInputValue('phoneNumber',newVal)
                    }
                );

                watch(  
                    () => form.verificationCode, // 依赖项  
                    (newVal) => { // 回调函数  
                        handleSureNumberInputValue('verificationCode',newVal)
                    }
                );

                watch(  
                    () => emailForm.verificationCode, // 依赖项  
                    (newVal) => { // 回调函数  
                        handleSureNumberInputValue('verificationCode',newVal)
                    }
                );
                

                // mock数据 区域 options

                const tabSelectItem = ref(undefined) // 选中的注册方式
                
                
                onMounted(() => {
                    tabSelectItem.value = 'phone' // 默认为手机号注册
                })

                const tokenCode = ref('')

                const phoneTimeInterval = ref(10) 
                const emailTimeInterval = ref(10) 
                const phoneAlreadSendMes = ref(false)
                const emailAlreadSendMes = ref(false)


                const handleVCodeText = (formType) => {
                    let label = '获取验证码'
                    if(formType === 'phone' && phoneAlreadSendMes.value) {
                        label = phoneTimeInterval.value + 's 后重发' 
                    }else if(formType === 'email' && emailAlreadSendMes.value) {
                        label = emailTimeInterval.value + 's 后重发'
                    }
                    return label
                }

                const pwsRulerLimit =  reactive({  // 密码约束
                    lengthConstraint: true,
                    typeConstraint: true,
                    charConstraint: true
                })

                const emailPwsRulerLimit =  reactive({  // 密码约束
                    lengthConstraint: true,
                    typeConstraint: true,
                    charConstraint: true
                })

                const phonePasswordRulerVisible = ref(false)
                const emailPasswordRulerVisible = ref(false)
                const phoneRuleFormRef = ref(null)
                const emailRuleFormRef = ref(null)
                /* 处理密码输入 */ 
                const handleInputPassword = (formType,value,callback) => {
                    if(!value) {
                        if(formType === 'phone') {
                            phonePasswordRulerVisible.value = false
                        }  else { emailPasswordRulerVisible.value = false }
                        return;
                    }
                    let pwsRuler;
                    let passwordRulerVisible;
                    if(formType === 'phone') {
                        pwsRuler = pwsRulerLimit 
                        handleFormInputValidate(phoneRuleFormRef.value,value,'password')
                        passwordRulerVisible = phonePasswordRulerVisible
                    } else {
                        pwsRuler = emailPwsRulerLimit 
                        handleFormInputValidate(emailRuleFormRef.value,value,'password')
                        passwordRulerVisible = emailPasswordRulerVisible
                    }

                    if(!/^.{8,20}$/.test(value)) {
                        pwsRuler.lengthConstraint = false
                    }else {
                        pwsRuler.lengthConstraint = true
                    }

                    if(!/^[a-zA-Z0-9!@#$%^&*()\-_+=,.<>/?':";{}[\]|\][\]|\\]*$/.test(value)) {
                        pwsRuler.charConstraint = false
                    }else {
                        pwsRuler.charConstraint = true
                    }

                    if(!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/.test(value)) {
                        pwsRuler.typeConstraint = false
                    }else {
                        pwsRuler.typeConstraint = true
                    }

                    // element 的校验
                    if(callback) {
                        if(!pwsRuler.lengthConstraint) {
                            callback(new Error('密码长度在 8 ~ 20 位'))
                        }else if(!pwsRuler.charConstraint) {
                            callback(new Error('仅支持字母、数字、特殊字符（除空格）'))
                        }else if(!pwsRuler.typeConstraint) {
                            callback(new Error('同时包含大、小写字母、数字'))   
                        }else {
                            callback() 
                        }
                    }else {
                        // 是否显示自定义校验 pop
                        const constraintKeys =  Object.keys(pwsRuler) 
                        const activeKey = constraintKeys.find(key => pwsRuler[key] === false)
                        if(activeKey) {
                            passwordRulerVisible.value = true
                        }else {
                            passwordRulerVisible.value = false
                        }
                    }
                }
                
                // 通用的 输入 处理表单验证方法 formEl ref 实例；value 值; key 字段值
                const handleFormInputValidate = (formEl,value,key) => {
                    if (!formEl) return;
                    if(value === '' ||  value === undefined || value === null) {
                        // formEl.validateField(key) 会报错 而formEl.validateField(key) 返回的是一个 promise 对象
                        formEl.validateField(key).then(res=>{}).catch(err=>{});
                    }else {
                        formEl.clearValidate(key)
                    }
                }

                const validatephone = (rule, value, callback) => {
                    if (!/^[0-9]{5,}$/.test(value)) {
                        callback(new Error('请输入正确的手机号！'))
                    } else {
                        callback()
                    }
                }

                const validateEmail = (rule, value, callback) => {
                    if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
                        // if (!/^([a-zA-Z0-9_-]{1,16})@([a-zA-Z0-9]{1,9})(\.[a-zA-Z0-9]{1,9}){0,3}(\.(?:com|net|org|edu|gov|mil|cn|us)){1,4}$/.test(value)) {
                        callback(new Error('请输入正确的邮箱！'))
                    } else {
                        callback()
                    }
                }

                const validatePwd = (rule, value, callback) => {
                    handleInputPassword('phone',value,callback)
                }

                const validateCheckPass = (rule, value, callback) => {
                    let password;
                    if(tabSelectItem.value === 'phone') {
                        password = form.password
                    }else {
                        password = emailForm.password
                    }
                    if (value.toString() !== password.toString()) {
                        callback(new Error('两次输入的密码不一致，请重新输入'));
                    } else {
                        callback();
                    }
                };

                // 表单验证规则
                const phoneRules = reactive({
                    phoneNumber: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: validatephone,trigger: 'blur'}
                    ],
                    verificationCode: [
                        {required: true, message: '请输入验证码', trigger: 'blur'},
                    ],
                    email: [{required: true,message: '请输入邮箱',trigger: 'blur'},
                            {validator: validateEmail,trigger: 'blur'}
                    ],
                    // password: [{required: true,message: '请输入密码',trigger: 'blur' },
                    //         {validator: validatePwd, trigger: 'blur' }],
                            
                    confirmPassword: [{ required: true,message: '请确认密码',trigger: 'blur'},{validator: validateCheckPass,trigger: 'blur'}
                    ],       
                })

                const handleBlurPopoverRuler = (key) => {
                    if(key === 'phone') {
                        phonePasswordRulerVisible.value = false
                    }else {
                        emailPasswordRulerVisible.value =  false
                    }
                }

                /* 点击注册按钮 */
                const isSubmitRequest = ref(false) 

                const router = useRouter()
                const handleClickSubmitButton = () => {
                    if(isSubmitRequest.value === true) {
                        return;
                    }
                    if(isCheckProtocol.value === false) {
                        ElMessage.error('请先勾选同意协议')
                        return;
                    }
                    const formEl = tabSelectItem.value === 'phone' ? phoneRuleFormRef.value : emailRuleFormRef.value
                    if(!formEl) return;
                    formEl.validate(async(valid) => {
                        if (valid) {
                            isSubmitRequest.value = true  // 开始加载
                            let params;
                            if(tabSelectItem.value === 'phone') {
                                params = {
                                    'action': 'register',
                                    'registerType': 'phoneregister',
                                    'preMobile': form.countryNum,
                                    'phonenumber': form.phoneNumber,
                                    'email': form.email,
                                    'yzm_code': form.verificationCode,
                                    'password': form.password,
                                    'password2': form.confirmPassword,
                                    'accepttophp': 'on',
                                }
                            }else {
                                params = {
                                    'action': 'register',
                                    'registerType': 'emailregister',
                                    'email': emailForm.email,
                                    'yzm_code': emailForm.verificationCode,
                                    'password': emailForm.password,
                                    'password2': emailForm.confirmPassword,
                                    'accepttophp': 'on',
                                }
                            }
                            try {
                                setTimeout(() => {
                                    isSubmitRequest.value = false
                                    ElMessage.success('注册成功！')
                                    setTimeout(() => {
                                        router.push('/login')
                                    },1500)
                                },1000)
                            } catch (error) {
                                isSubmitRequest.value = false
                                ElMessage.error('服务接口或者网络异常，请稍后再试！')
                            }
                        } 
                    })
                }


</script>

<template>
         <div class="layout-wrapper">
            <div class="layout-content">
                <div class="layout-left">
                    <div class="layout-header">
                        <a href="/" class="layout-header-logo"></a>
                    </div>
                    <div class="layout-introduce-content">
                        <h1 class="layout-introduce__title">
                            ToDoList
                        </h1>
                        <p class="layout-introduce__desc">
                            个人任务管理工具
                        </p>
                        <p class="layout-introduce__copyright">
                            版权所有© 重庆大学城市科技学院 李劲林
                        </p>
                    </div>
                </div>
                <div class="layout-right">
                    <div class="layout-form">
                        <div class="layout-form-title">
                            注册 个人任务管理工具 账号
                        </div>
                        <div class="layout-form-tabs mt-16 fboxYcenter">
                            <!-- <div class="form-tab__item" @click="tabSelectItem = 'email'" :class="{'is-active': tabSelectItem === 'email'}">
                                邮箱注册
                            </div> -->
                            <div class="form-tab__item" @click="tabSelectItem = 'phone'" :class="{'is-active': tabSelectItem === 'phone'}" >
                                手机号注册
                            </div>
                        </div>
                        <div class="layout-form-content">
                            <el-form @keyup.enter="handleClickSubmitButton"  v-show="tabSelectItem === 'phone'" :class="{'el-form--active': tabSelectItem === 'phone'}" :model="form" ref="phoneRuleFormRef" :rules="phoneRules">
                                <el-form-item autocomplete="off"  prop="phoneNumber">
                                    <el-input
                                    @input="handleFormInputValidate(phoneRuleFormRef,form.phoneNumber,'phoneNumber')"
                                    v-model="form.phoneNumber"
                                    placeholder="请输入手机号码"
                                    class="input-with-select"
                                    clearable
                                    >
                                    </el-input>
                                </el-form-item>
                                <el-form-item autocomplete="off" prop="email">
                                    <el-input @input="handleFormInputValidate(phoneRuleFormRef,form.email,'email')" placeholder="请输入邮箱" v-model="form.email" clearable></el-input>
                                </el-form-item>

                                <el-form-item autocomplete="off" prop="password">
                                    <el-input @blur="handleBlurPopoverRuler('phone')" @focus="handleInputPassword('phone',form.password)" @input="handleInputPassword('phone',$event)" type="password"
                                        placeholder="请设置密码" v-model="form.password" clearable show-password>
                                        </el-input>
                                </el-form-item>

                                <el-form-item autocomplete="off" prop="confirmPassword">
                                    <el-input type="password" placeholder="请确认密码" v-model="form.confirmPassword" @input="handleFormInputValidate(phoneRuleFormRef,form.confirmPassword,'confirmPassword')" clearable show-password>
                                    </el-input>
                                </el-form-item>
                            </el-form>
                            <el-form @keyup.enter="handleClickSubmitButton" v-show="tabSelectItem === 'email'" :class="{'el-form--active': tabSelectItem === 'email'}" :model="emailForm" ref="emailRuleFormRef" :rules="phoneRules">
                                <el-form-item autocomplete="off" prop="email">
                                    <el-input @input="handleFormInputValidate(emailRuleFormRef,emailForm.email,'email')" placeholder="请输入邮箱" v-model="emailForm.email" clearable></el-input>
                                </el-form-item>
                                <el-form-item autocomplete="off" prop="password">
                                    <el-popover
                                    placement="bottom-start"
                                    :visible="emailPasswordRulerVisible"
                                    :width="280"
                                    popper-class="rulerpopper"
                                    >
                                    <template #reference>
                                        <el-input @blur="handleBlurPopoverRuler('email')" @focus="handleInputPassword('email',emailForm.password)" @input="handleInputPassword('email',$event)" type="password"
                                        placeholder="请设置密码" v-model="emailForm.password" clearable show-password>
                                        </el-input>
                                    </template>
                                    <template #default>
                                        <ul class="popoverRuler-ul">
                                            <li class="popoverRuler-li fboxRow">
                                                <template v-if="!emailPwsRulerLimit.lengthConstraint">
                                                    <el-icon class="circleClose">
                                                        <circle-close-filled />
                                                    </el-icon>
                                                </template>
                                                <template v-else>
                                                    <el-icon class="successFilled">
                                                        <success-filled />
                                                    </el-icon>
                                                </template>
                                                <div class="popoverRuler-li__text ml-8">
                                                    密码长度在 8 ~ 20 位
                                                </div>
                                            </li>

                                            <li class="popoverRuler-li fboxRow">
                                                <template v-if="!emailPwsRulerLimit.typeConstraint">
                                                    <el-icon class="circleClose">
                                                        <circle-close-filled />
                                                    </el-icon>
                                                </template>
                                                <template v-else>
                                                    <el-icon class="successFilled">
                                                        <success-filled />
                                                    </el-icon>
                                                </template>
                                                <div class="popoverRuler-li__text ml-8">
                                                    同时包含大、小写字母、数字
                                                </div>
                                            </li>

                                            <li class="popoverRuler-li fboxRow">
                                                <template v-if="!emailPwsRulerLimit.charConstraint">
                                                    <el-icon class="circleClose">
                                                        <circle-close-filled />
                                                    </el-icon>
                                                </template>
                                                <template v-else>
                                                    <el-icon class="successFilled">
                                                        <success-filled />
                                                    </el-icon>
                                                </template>
                                                <div class="popoverRuler-li__text ml-8">
                                                    仅支持字母、数字、特殊字符（除空格）
                                                </div>
                                            </li>
                                        </ul>
                                    </template>
                                    </el-popover>
                                </el-form-item>

                                <el-form-item autocomplete="off" prop="confirmPassword">
                                    <el-input type="password" placeholder="请确认密码" v-model="emailForm.confirmPassword" @input="handleFormInputValidate(emailRuleFormRef,emailForm.confirmPassword,'confirmPassword')" clearable show-password>
                                    </el-input>
                                </el-form-item>
                            </el-form>
                            
                            <div class="layout-form__check fboxYcenter">
                                <el-checkbox style="margin-right: 4px" class="mr-4" v-model="isCheckProtocol" size="large" />
                                 
                                我已阅读并同意<div class="mainColor">个人系统服务协议</div>
                            </div>

                            <div id="tncodeaccess_str" style="display: none;"></div>
						    <div class="tncode" style="display: none;text-align: center;width: 100%;"></div>
                        </div>
                        <div class="layout-form-button_wrap mt-16">
                            <div @click="handleClickSubmitButton" :class="{'tpm-btn__loadding': isSubmitRequest }" class="tpm-btn tpm-btn--primary w100">
                                {{ isSubmitRequest ? '提交请求中' : '同意协议并提交' }}
                            </div>
                        </div>
                        <p class="layout-form-goto">
                            已有账号？<a href="/login.shtml" target="_self" class="mainColor">立即登录</a> 
                        </p>
                    </div>
                </div>
            </div>
       </div>  
</template>

<style scoped>
.layout-wrapper {
    height: 100vh;
    min-width: 1300px;
    background: linear-gradient(to right, #F6F9FF 50%, #006eff 50%);
}
.layout-wrapper .layout-content {
    max-width: 1920px;
    margin: auto;
    display: flex;
    height: 100%;
    position: relative;
}

.layout-wrapper .layout-content .layout-left {
    position: relative;
    flex: 1;
    background: #F6F9FF;
}

.layout-wrapper .layout-content .layout-right {
    flex: 0 0 27.81%;
    position: relative;
    background: #006eff;
}


.layout-wrapper .layout-form {
    position: absolute;
    top: 50%;
    left: -50%;
    transform: translate(50px,-50%);
    width: 400px;
    box-sizing: border-box;
    padding: 48px 40px;
    background: #FFFFFF;
    box-shadow: 0px 0px 24px 0px rgba(34,28,25,0.1);
    border-radius: 8px;
}

.layout-header {
    position: absolute;
    height: 76px;
    left: 0;
    top: 0;
    width: 100%;
}

.layout-header .layout-header-logo {
    position: absolute;
    top: 0;
    left: 32px;
    bottom: 0;
    display: block;
    width: 45px;
    height: 45px;
    margin: auto 0;
    overflow: hidden;
    background: url(../assets/img/logo.jpg) center no-repeat;
    background-size: 100%;
}

.layout-introduce-content {
    height: 490px;
    position: absolute;
    top: 50%;
    transform: translateY(calc(-50% + 120px));
    right: 0px;
    margin-right: 35%;
}

.layout-introduce-content  .layout-introduce__title {
    height: 58px;
    font-size: 48px;
    font-weight: bold;
    color: var(--titleColor);
    line-height: 56px;
}

.layout-introduce-content .layout-introduce__desc {
    font-family: 'AlimamaShuHeiTi-Bold';
    font-size: 48px;
    color: var(--titleColor);
    line-height: 56px;
    margin-top: 3px;
}

.layout-introduce-content .layout-introduce__copyright {
    margin-top: 140px;
    font-size: 14px;
    font-weight: 600;
    color: #4C5B76;
    line-height: 16px;
}

.layout-form .layout-form-title  {
    font-size: 24px;
    font-weight: 600;
    color: #020814;
    line-height: 28px;
}

.layout-form-tabs .form-tab__item {
    font-size: 16px;
    color: #020814;
    position: relative;
    cursor: pointer;
}

.layout-form-tabs .form-tab__item + .form-tab__item {
    margin-left: 40px;
}


.layout-form-tabs .form-tab__item.is-active {
    color: #006eff;
    font-weight: 600;
}

.layout-form-tabs .form-tab__item.is-active::after {
    content: '';
    display: block;
    position: absolute;
    left: 50%;
    bottom: -8px;
    transform: translateX(-50%);
    width: 0px;
    height: 4px;
    background: #006eff;
    border-radius: 8px;
    animation: activeTabItem 0.3s ease-in 1 0s;
	animation-fill-mode: forwards;
}


@keyframes activeTabItem {
    0% {
        width: 0px;
    }

    100% {
        width: 32px;
    }
}

.layout-form .layout-form-content {
    margin-top: 30px;
}

.layout-form .layout-form-tabs {
    line-height: 22px;
}

.layout-form .el-input .el-input__inner {
    color: #020814;
    /* 加上上下共 2px 的边框高度就是 设计稿 40px 的高度 */
    height: 38px; 
}

.el-form-item .tpm-btn {
    width: 152px;
    flex:  0 0 152px;
    height: 40px;
    line-height: 40px;
}

.tpm-btn.tpm-btn__sendVCode:not(.noclick) {
    border: 1px solid #DCE2EB;
    color: #020814;
    background: transparent;
    box-shadow: none;
    border-radius: 4px;
}

.tpm-btn.tpm-btn__sendVCode:not(.noclick):hover {
    border-color: var(--mainColor);
    color: var(--mainColor);
}

.tpm-btn.noclick {
    cursor: not-allowed;
}

.layout-form__check a:hover , .layout-form-goto a:hover {
    text-decoration: underline;
}

.layout-form__check .el-checkbox__label,.layout-form__check .el-checkbox__input.is-checked+.el-checkbox__label  {
    color: #41464F;
}

.layout-wrapper_login .layout-form-button_wrap {
    margin-top: 60px;
}

.layout-form-button_wrap .tpm-btn {
    height: 42px;
    line-height: 42px;
    border-radius: 20px;
}

.layout-form-button_wrap .tpm-btn.tpm-btn__loadding {
    opacity: 0.45;
    cursor: default;
}

.layout-form-goto {
    margin-top: 24px;
    text-align: center;
    font-size: 14px;
    line-height: 20px;
}

.layout-form-goto.layout-form-goto__login {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 20px;
}

.form-goto-register {
    color: #A5B1C7;
}

.form-goto-forgetPwd {
    font-size: 14px;
    font-weight: 600;
    color: #020814;
}

.layout-form-goto.layout-form-goto__login .form-goto-forgetPwd:hover {
    text-decoration: none;
}

.v-enter-from {
    transform: translateX(-40px);
}

.v-enter-active{
    transition: transform 0.3s ease-in;
}

.v-enter-to {
    transform: translateX(0px);
}


.el-form--active {
    animation: fadeToleft 0.3s ease-out 1 0s;
	animation-fill-mode: forwards;
}

.layout-form-content .el-input__suffix .el-input__icon{
    color: #333;
}

@keyframes fadeToleft {
    0% {
        transform: translateX(-20px);
        opacity: 0;
    }

    100% {
        transform: translateX(0px);
        opacity: 1;
    }
}

@media screen and (max-width: 1400px) {
    .layout-wrapper .layout-form {
        transform: translate(0px,-50%);
    }
}

</style>
